package com.lujianfei.powersearch.ui.search.viewmodel

import android.text.TextUtils
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableBoolean
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.lujianfei.powersearch.database.SearchItemModel
import com.lujianfei.powersearch.utils.DatabindingDiffUtils
import com.lujianfei.powersearch.utils.LogUtils
import com.orm.SugarRecord
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class SearchActivityViewModel: ViewModel() {

    private val TAG = "SearchActivityViewModel"

    val data = ObservableArrayList<SearchItemModel>()

    private val searchItemModels = arrayListOf<SearchItemModel>()

    var onItemClickCallback: ((SearchItemModel) -> Unit)?= null
    val onItemClick: ((SearchItemModel) -> Unit) = {
        onItemClickCallback?.invoke(it)
    }
    var onItemLongClickCallback: ((SearchItemModel) -> Unit)?= null
    val onItemLongClick: ((SearchItemModel) -> Unit) = {
        onItemLongClickCallback?.invoke(it)
    }
    var onLinkClickCallback: ((String) -> Unit)?= null
    val onLinkClick: ((String) -> Unit) = {
        onLinkClickCallback?.invoke(it)
    }

    val loading = ObservableBoolean(false)

    var lastSearch = ""

    fun search(searchText: String, parentId: Long, research:Boolean = false) {
        if (research) {
            lastSearch = ""
        }
        if (loading.get()) {
            lastSearch = searchText
            return
        }
        if (TextUtils.isEmpty(searchText)) {
            data.clear()
            return
        }
        loading.set(true)
        viewModelScope.launch {
            val searchResult = withContext(Dispatchers.IO) {
                val result = arrayListOf<SearchItemModel>()
                kotlin.runCatching {
                    // 遍历子项并加入集合
                    searchItemModels.clear()
                    val models = SugarRecord.find(SearchItemModel::class.java, "parentId=?", "" + parentId)
                    if (null != models) {
                        searchItemModels.addAll(models)
                        for (d in models) {
                            travalise(d, searchText, 1)
                        }
                    }
                    searchItemModels.forEach{
                        LogUtils.d(TAG, "searchItemModels: ${it.name}  ${it.keywords}  ${it.level}")
                    }
                    // 对集合进行条件过滤
                    val tmp = searchItemModels.filter {
                        it.name?.contains(searchText) == true ||
                                it.keywords?.contains(searchText) == true
                    }.sortedBy { it.level }.toList()

                    // 对集合进行去重处理
                    for (t in tmp) {
                        if (result.find { it.id == t.id } == null) {
                            result.add(t)
                        }
                    }
                }
                result
            }
            DatabindingDiffUtils.setData(oldList = data, newList = searchResult)
            loading.set(false)

            if (lastSearch.isNotBlank()) {
                search(lastSearch, parentId , research = true)
            }
        }
    }

    private fun travalise(root: SearchItemModel, searchText: String?, level: Int) {
        val models = SugarRecord.find(SearchItemModel::class.java, "parentId=?", "" + root.id)
        if (null != models && models.isNotEmpty()) {
            for (d in models) {
                d.level = level
                travalise(d, searchText, level + 1)
            }
            searchItemModels.addAll(models)
        }
    }

    fun reloadItem(id: Long) {
        val updateIndex = data.indexOfFirst { it.id == id }
        if (updateIndex == -1) {
            return
        }
        val item = SugarRecord.findById(SearchItemModel::class.java, id)
        if (item == null) {
            return
        }
        data.set(updateIndex, item)
    }
}